1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| <?php $arr=[ ['id' => 1, 'text' => 'Parent 1', 'pid' => 0], ['id' => 2, 'text' => 'Parent 2', 'pid' => 0], ['id' => 3, 'text' => 'Parent 3', 'pid' => 0], ['id' => 4, 'text' => 'Child 1', 'pid' => 1], ['id' => 5, 'text' => 'Parent 4', 'pid' => 0], ['id' => 6, 'text' => 'Child 2', 'pid' => 1], ['id' => 7, 'text' => 'Child 3', 'pid' => 1], ['id' => 8, 'text' => 'Parent 5', 'pid' => 0], ['id' => 9, 'text' => 'Child 1', 'pid' => 2], ['id' => 10, 'text' => 'Child 4', 'pid' => 1], ['id' => 11, 'text' => 'Child 1', 'pid' => 5], ['id' => 12, 'text' => 'GrandChild 1', 'pid' => 10] ];
class createTree { private static $table = [];
private function __construct() {}
private static function tree($pid = 0) { $tree = array(); foreach (self::$table as $row) { if ($row['pid'] === $pid) { $tmp = self::tree($row['id']); if ($tmp) { $row['children'] = $tmp; } $tree[] = $row; } } return $tree; }
public static function get($table) { self::$table = $table; return self::tree(); } }
var_dump(createTree::get($arr));
|